package com.mt.baseinfo.until;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

@Component
@Aspect
@Slf4j
/*
    延迟双删
*/
public class DoubleClearCacheAop {

    /*@Autowired
    private UserService userService;
    //声明一个用于延时的定时线程池代替线程sleep
    ScheduledExecutorService task = new ScheduledThreadPoolExecutor(10, new BasicThreadFactory.
            Builder().namingPattern("clearCache-schedule-pool-%d").build());

    @Pointcut("@annotation(com.mt.baseinfo.until.ClearCache)")
    private void clearCachePoint() {
    }

    @Around("clearCachePoint()")
    public Object clearCacheAop(ProceedingJoinPoint proceeds) throws Throwable {
        Method method = ((MethodSignature) proceeds.getSignature()).getMethod();
        ClearCache annotation = method.getAnnotation(ClearCache.class);
        Object proceed = null;
        //如果清除注解开启了
        if (annotation.open()) {
            //上下文获取信息
            IPubUser user = MsySecurityContextHolder.getUser();
            if (Objects.nonNull(user)) {
                //执行清除缓存的动作
                userService._clearCache(user);
                //业务处理
                proceed = proceeds.proceed();
                //延时两秒后再删
                task.schedule(() -> {
                    userService._clearCache(user);
                    if (log.isInfoEnabled()) {
                        log.info(Thread.currentThread().getName() + ":double delete cache completed");
                    }
                }, 2L, TimeUnit.SECONDS);
            } else {
                proceed = proceeds.proceed();
            }
        }
        return proceed;
    }*/
}